<!-- 这是报警复核的页面 -->
<template>
	<div class="alarm-review">
		<div class="page-region">
			<div class="basic-region">
				<div class="basic-region-left">
					<div class="left-action-box">
						<div class="device-part">
							<a-select
								ref="select"
								v-model:value.trim="mAlgorithmIdList"
								style="margin-right: 12px"
								:options="AIServiceList"
								class="select-item"
								:class="[mAlgorithmIdList.length && 'active']"
								mode="multiple"
								placeholder="AI服务"
								max-tag-count="responsive"
								@change="handleSearch('mAlgorithmIdList')"
							></a-select>

							<a-tree-select
								v-model:value="cameraTreeList"
								style="margin-right: 12px"
								:tree-data="cameraTreeData"
								:dropdown-match-select-width="dropdownMatchSelectWidth"
								class="select-item"
								:class="[cameraTreeList.length && 'active']"
								max-tag-count="responsive"
								allow-clear
								tree-checkable
								:field-names="{
									children: 'children',
									label: 'name',
									value: 'id'
								}"
								tree-node-filter-prop="name"
								:show-checked-strategy="SHOW_PARENT"
								placeholder="场景区域/摄像头"
								@change="changeCameraTreeList"
							></a-tree-select>

							<a-cascader
								v-model:value="boxSerialList"
								class="select-item"
								:loading="cameraListLoading"
								:class="[boxSerialList.length && 'active']"
								max-tag-count="responsive"
								multiple
								:options="boxDeviceList"
								:field-names="{
									label: 'label',
									value: 'id',
									children: 'children'
								}"
								expand-trigger="hover"
								placeholder="盒子/摄像头"
								allow-clear
								show-arrow
								@change="changeBoxSerialList"
							>
								<template #label="data">
									{{ data }}
								</template>
							</a-cascader>
						</div>

						<div class="time-part">
							<ul class="select-list">
								<li
									:key="item.value"
									v-for="(item, index) in presetTime"
									class="select-list-item"
									:class="[activeTimeIndex === index && 'active']"
									@click="changeTime(index, item.value)"
								>
									{{ item.text }}
								</li>
							</ul>

							<a-range-picker
								format="YYYY-MM-DD HH:mm"
								class="range-picker"
								value-format="YYYY-MM-DD HH:mm"
								:value="[createBeginVal, createEndVal]"
								show-time
								:class="[createBeginVal && createBeginVal && 'active']"
								:placeholder="['开始时间', '结束时间']"
								input-read-only
								@calendar-change="changeRangePicker"
							>
								<template #suffixIcon> <clock-circle-outlined></clock-circle-outlined></template
							></a-range-picker>

							<div class="reset" @click="reset">
								<div>
									<global-svg-icon icon-name="reset" style="margin-right: 4px" width="14px" height="14px"></global-svg-icon>
									重置
								</div>
							</div>
						</div>
					</div>
				</div>
				<div class="basic-region-right">
					<ul class="select-list">
						<li
							:key="item.value"
							v-for="(item, index) in auditingList"
							class="select-list-item"
							:class="[activeAuditingIndex === index && 'active']"
							@click="changeAuditing(index, item.value)"
						>
							{{ item.text }}
						</li>
					</ul>
				</div>
			</div>

			<div class="review-container">
				<div v-if="activeAuditingIndex === 0 && !props.alarmreviewSwitch" class="disable-prompts-text">
					<global-svg-icon icon-name="question-fill" width="24px" height="24px" style="margin-right: 5px"></global-svg-icon>
					<div>右上角”报警复核“按钮已关闭，请开启后使用该功能</div>
				</div>

				<div style="height: 100%">
					<pending-review
						ref="pendingReviewRef"
						v-if="activeAuditingIndex === 0 && props.alarmreviewSwitch"
						:table-attr="tableAttr"
					></pending-review>
					<findings-audit v-if="activeAuditingIndex === 1" :status="1" :table-attr="tableAttr" @change="changeTable"></findings-audit>
					<findings-audit v-if="activeAuditingIndex === 2" :status="2" :table-attr="tableAttr"></findings-audit>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts" name="alarm-review">
import { TreeSelect } from 'ant-design-vue';
import { g6UseTable } from 'glasssix-vue3-hooks';
import { arr2Str } from '@/global-utils/base.utils';
import { AlarmCenterAPI } from '../../../api';
import { TsSelectOptItem } from '../../../type';
import { PendingReview, FindingsAudit } from '../../index';
import dayjs from 'dayjs';

const props = withDefaults(defineProps<{ alarmreviewSwitch: boolean }>(), {
	alarmreviewSwitch: false
});

const emits = defineEmits<{
	(e: 'update:value', value: any): void;
}>();

const pendingReviewRef = ref();

const { tableAttr, setTableData } = g6UseTable(AlarmCenterAPI.list, {
	pageSize: 50
});
const activeAuditingIndex = ref<number>(0);
const SHOW_PARENT = TreeSelect.SHOW_PARENT;
const changeTable = () => {
	emits('update:value', tableAttr);
};

/**
 * -----------------------搜索-----------------------
 */
// AI服务下拉数据
const mAlgorithmIdList = ref<string[]>([]);
const AIServiceList = ref<TsSelectOptItem[]>([]);
const getAIServiceList = async (): Promise<void> => {
	let { data } = await AlarmCenterAPI.AIServiceList();
	AIServiceList.value = data;
};

// 场景区域/摄像头下拉数据
const dropdownMatchSelectWidth = ref<number>(500);
// 回显页面的
const cameraTreeList = ref([]);
// 传给后端区域id的
const mAreaIdList = ref<any>([]);
// 传给后端的设备id
const areDeviceIdList = ref<string[]>([]);
// 下拉数据
const cameraTreeData = ref<any>([]);
const getDeviceList = async (): Promise<void> => {
	let { data } = await AlarmCenterAPI.getDeviceList();
	cameraTreeData.value = filterTreeDelDisable(data);
};
// 取消所有禁用
const filterTreeDelDisable = (tree: any) => {
	tree.forEach((item: any, index: any, arr: any) => {
		item.disabled = false;
		if (item.children) {
			arr[index].children = filterTreeDelDisable(item.children);
		}
	});
	return tree;
};
// 盒子/摄像头下拉数据
// 回显页面的
const boxSerialList = ref<string[]>([]);
const cameraListLoading = ref<boolean>(false);
// 传给后端的盒子序列号
const boxSerialListVal = ref<string[] | number[]>([]);
// 传给后端的设备id
const boxDeviceIdList = ref<string[] | number[]>([]);
// 下拉数据
const boxDeviceList = ref<any>([]);
const getBoxDeviceList = async (): Promise<void> => {
	let { data } = await AlarmCenterAPI.boxDeviceList();
	boxDeviceList.value = data;
};

// 时间过滤
const createBeginVal = ref<any>();
const createEndVal = ref<any>();

// 预设时间段
const presetTime = ref<any>([
	{ text: '今日', value: 1 },
	{ text: '近7天', value: 7 },
	{ text: '近30天', value: 30 }
]);
const activeTimeIndex = ref<number>(0);

// 查询
const handleSearch = (key?: string): void => {
	switch (key) {
		case 'mAlgorithmIdList':
			tableAttr.searchObj.mAlgorithmIdList = arr2Str(mAlgorithmIdList.value);

			break;
		case 'mAreaOrDeviceIdList':
			tableAttr.searchObj.mAreaIdList = arr2Str(mAreaIdList.value);
			tableAttr.searchObj.areDeviceIdList = arr2Str(areDeviceIdList.value);

			break;
		case 'boxSerialListVal':
			tableAttr.searchObj.boxDeviceIdList = arr2Str(boxDeviceIdList.value as string[] | number[]);
			tableAttr.searchObj.boxSerialList = arr2Str(boxSerialListVal.value as string[] | number[]);

			break;

		default:
			break;
	}

	setTableData(true);
};

/* ------------------- 处理时间选择逻辑 ------------------ */

// 根据传入的天数，获取以当前时间基准的时间范围
const GetTimeRange = (day: number, init: boolean = true): void => {
	const createBegin = dayjs()
		.subtract(day - 1, 'days')
		.startOf('day')
		.format('YYYY-MM-DD HH:mm:ss');
	const createEnd = dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss');

	tableAttr.searchObj.startTime = createBegin;
	tableAttr.searchObj.endTime = createEnd;
	createBeginVal.value = undefined;
	createEndVal.value = undefined;
	tableAttr.current = 1;
	if (init) {
		handleSearch();
	}
};
const changeRangePicker = (dates: any, date: string[]): void => {
	activeTimeIndex.value = -1;
	if (date && date.length) {
		if (date[0] !== '') {
			tableAttr.searchObj.startTime = `${date[0]}:00`;

			createBeginVal.value = `${date[0]}`;
		}
		if (date[1] !== '') {
			tableAttr.searchObj.endTime = `${date[1]}:59`;
			createEndVal.value = `${date[1]}`;
		}
		if (date[0] === '' && date[1] === '') {
			activeTimeIndex.value = 0;
			GetTimeRange(1, false);
			createBeginVal.value = undefined;
			createEndVal.value = undefined;
		}

		tableAttr.current = 1;
		handleSearch();
	}
};

// 重置
const reset = (): void => {
	tableAttr.searchObj = {};
	mAlgorithmIdList.value = [];
	cameraTreeList.value = [];
	boxSerialList.value = [];
	activeTimeIndex.value = 0;
	GetTimeRange(1, false);
	tableAttr.searchObj.auditType = activeAuditingIndex.value;
	setTableData(true);
};
const changeTime = (index: number, day: number): void => {
	// 如果是同一天不搜索
	if (index === activeTimeIndex.value) {
		return;
	}
	activeTimeIndex.value = index;
	GetTimeRange(day);
};
/* ------------------- 处理筛选区域的多选框逻辑 ------------------ */
// 递归筛选
const findObjectById = (data: any, id: string): any => {
	for (let i = 0; i < data.length; i++) {
		const obj = data[i];
		if (obj.id === id) {
			return obj;
		}
		if (obj.children && obj.children.length > 0) {
			const result = findObjectById(obj.children, id);
			if (result) {
				return result;
			}
		}
	}
	return null;
};

const flatten = (data: any): any => {
	return data.reduce((prev: any, cur: any) => {
		prev.push({
			areaOrDeviceId: cur.areaOrDeviceId,
			name: cur.name,
			type: cur.type
		});
		if (cur.children) {
			prev.push(...flatten(cur.children));
		}
		return prev;
	}, []);
};

// 场景区域/摄像头的值改变时
const changeCameraTreeList = (value: any): void => {
	mAreaIdList.value = [];
	areDeviceIdList.value = [];
	value.forEach((item: any) => {
		const re = findObjectById(cameraTreeData.value, item);
		// type为1时代表选择区域,则把区域id和摄像头id都传入
		if (re.type === 1) {
			const flatData = flatten(re.children ? re.children : [re]);
			if (re.children) {
				flatData.forEach((i: any) => {
					if (i.type === 1) {
						mAreaIdList.value.push(i.areaOrDeviceId);
					} else {
						areDeviceIdList.value.push(i.areaOrDeviceId);
					}
				});
			}
			mAreaIdList.value.push(re.areaOrDeviceId);
		}
		// type为0时代表选择摄像头，只传摄像头id
		if (re.type === 0) {
			areDeviceIdList.value.push(re.areaOrDeviceId);
		}
	});
	handleSearch('mAreaOrDeviceIdList');
};

// 处理盒子/摄像头
const changeBoxSerialList = (value: any): void => {
	boxDeviceIdList.value = [];
	boxSerialListVal.value = [];
	value.forEach((item: any) => {
		const re = findObjectById(boxDeviceList.value, item[item.length - 1]);
		// 选中盒子时将所有子项的deviceId获取到
		if (re.children) {
			re.children.forEach((itemChild: any) => {
				boxDeviceIdList.value.push(itemChild.deviceId as never);
			});
			boxSerialListVal.value.push(re.boxSerial as never);
		} else {
			// 选中子项时直接把deviceId获取到
			boxDeviceIdList.value.push(re.deviceId as never);
		}
	});
	handleSearch('boxSerialListVal');
};

/* ------------------- 结束 ------------------ */

// ----------------------------------左侧列表的操作----------------------------------------------
const auditingList = ref<any>([
	{ text: '待审核', value: 0 },
	{ text: '已通过', value: 1 },
	{ text: '未通过', value: 2 }
]);
const changeAuditing = (index: number, item: number): void => {
	if (index === activeAuditingIndex.value) {
		return;
	}

	activeAuditingIndex.value = index;
	tableAttr.searchObj.auditType = item;
	reset();
};
// =====================================================
const init = (): void => {
	tableAttr.searchObj.auditType = 0;
	getAIServiceList();
	getBoxDeviceList();
	getDeviceList();
	GetTimeRange(1, false);

	// setTableData();
};

onMounted(() => {
	init();
});
</script>

<style lang="less" scoped>
.flex {
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.alarm-review {
	.page-region {
		width: 100%;
		height: calc(100vh - 125px);
		padding: 28px 0 24px;

		.basic-region {
			display: flex;
			justify-content: space-between;

			.basic-region-left {
				display: grid;
				grid-auto-flow: column;
				grid-column-gap: 32px;
				align-items: center;

				.left-action-box {
					display: flex;

					.device-part {
						margin-right: 12px;

						.select-item {
							width: 180px;

							&.active {
								width: 285px;
							}
						}

						:deep(.ant-select) {
							.ant-select-selector {
								height: 36px !important;
							}
						}
					}

					.time-part {
						display: flex;

						.select-list {
							display: flex;
							// width: 280px;
							height: 36px;
							margin: 0 12px 0 0;
							border: 1px solid @mask02;
							border-radius: 6px;
							padding: 3px 0;
							font-size: 14px;
							line-height: 22px;
							color: @text02;
							flex-shrink: 0;

							.select-list-item {
								position: relative;
								width: 87px;
								margin: 0 3px;
								border-radius: 4px;
								padding: 3px 0;
								text-align: center;
								// line-height: 36px;
								cursor: pointer;

								&.active {
									color: @text01;
									background: @primary01;

									&:hover {
										background: @primary02 !important;
									}

									&:active {
										background: @primary03 !important;
									}
								}
								// 分割线
								&::after {
									position: absolute;
									top: 50%;
									right: -6px;
									width: 1px;
									height: 14px;
									margin-right: 3px;
									background: @borderColor02;
									transform: translateY(-50%);
									content: '';
								}

								&:last-child {
									&::after {
										display: none;
									}
								}
							}
						}

						.range-picker {
							width: 250px;
							flex-shrink: 0;

							svg {
								color: red;
							}

							&.active {
								width: 308px;
							}
						}
					}
				}

				.reset {
					display: flex;
					margin: 0 12px;
					color: @text03;
					cursor: pointer;
					flex-direction: column;
					justify-content: center;
				}

				button {
					margin-left: 16px;
				}
			}

			.basic-region-right {
				.select-list {
					display: flex;
					width: 214px;
					height: 36px;
					margin: 0 8px 0 0;
					margin-right: 32px;
					border: 1px solid @borderColor02;
					border: 1px solid @mask02;
					border-radius: 31px;
					padding: 3px;
					font-size: 14px;
					line-height: 32px;
					color: @text03;
					background: @background02;

					.select-list-item {
						display: flex;
						// position: relative;
						width: 66px;
						border-radius: 38px;
						padding: 4px 12px;
						box-shadow:
							0 1px 3px 0 rgba(37, 37, 45, 0.14),
							0 2px 8px 0 rgba(37, 37, 45, 0.14);
						cursor: pointer;
						justify-content: center;
						align-items: center;
						gap: 10px;
						align-self: stretch;

						&:hover {
							color: @text02;
							background: @mask03;
						}

						&.active {
							font-size: 14px;
							font-weight: 700;
							font-style: normal;
							line-height: 22px; /* 157.143% */
							text-align: center;
							color: @text01;
							background: @borderColor02;
						}
					}
				}
			}
		}
	}

	.review-container {
		// display: flex;
		// align-items: center;
		// justify-content: center;
		height: 100%;

		.disable-prompts-text {
			display: flex;
			margin-top: 233px;
			font-size: 14px;
			font-weight: 400;
			font-style: normal;
			line-height: 22px; /* 157.143% */
			color: @text03;
			align-items: center;
			justify-content: center;
		}
	}
}
</style>
